/*
 * Copyright (c) 1999 2000
 * Information Promotion Agency of Japan (IPA),
 * Fujitsu Limited, and 
 * Matsuoka Laboratory, Tokyo Institute of Technology
 * All rights reserved.
 *
 * Redistribution and non-commercial use in source and binary forms, 
 * with or without modification, are permitted provided that the following 
 * conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * 3. All advertising materials mentioning features or use of this 
 *    software must display the following acknowledgement:
 *
 *    This product includes software developed by Information Promotion Agency
 *    of Japan, Fujitsu Limited, and Matsuoka Laboratory, 
 *    Tokyo Institute of Technology.
 *
 * 4. The names "Information Promotion Agency", "Fujitsu Limited",
 *    "Matsuoka Laboratory", or "Tokyo Institute of Technology" should
 *    not be used to endorse or promote products derived from this
 *    software without specific prior written permission.
 *
 * 5. Any use of the source code or the binary in a commercial product, 
 *    whether may it be the origial representation or in some modified form,
 *    is not permitted without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 * $Revision: 1.4 $
 * $Date: 2000/02/23 08:43:37 $
 * $Author: kouya $
 */

package org.OpenJIT;

import java.io.*;
import java.util.*;
import java.net.*;
import sun.net.www.protocol.http.HttpURLConnection;

public class OpenJITLoader extends ClassLoader {
    static private Properties props;
    static private boolean verbose;

    /* Class initializer */
    static {
	props = new Properties();

	try {
	    File file = new File("OpenJIT.properties");
	    FileInputStream in = new FileInputStream(file);
	    props.load(in);
	    in.close();
	    // this.list(System.err);
	} catch(Exception e) {
	}
    }

    public static String getProperty(String key) {
	String str = props.getProperty(key);
	if (str == null)
	    str = System.getProperty(key);
	return str;
    }

    public static boolean getPropertyBoolean(String key, boolean default_value) {
	String str = getProperty(key);
	if (str == null)
	    return default_value;
	if (str.compareTo("true") == 0)
	    return true;
	if (str.compareTo("false") == 0)
	    return false;
	return default_value;
    }

    URL base;

    public OpenJITLoader(URL base) {
	this.base = base;
    }

    protected Class loadClass(String name, boolean resolve) 
                    throws ClassNotFoundException {
	Class cl = findLoadedClass(name);
	if (cl == null) {
	    if (name.regionMatches(0, "org.OpenJIT.", 0, 12)) {
		try {
		    String cname = name.replace('.', '/') + ".class";
		    URL url = new URL(base, cname);
		    cl = loadClass(name, url);
		} catch (IOException e) { e.printStackTrace(); }
	    } else {
		try {
		    return findSystemClass(name);
		} catch (ClassNotFoundException e) { }
	    }
	}
	if (cl == null) {
	    throw new ClassNotFoundException(name);
	}
	if (resolve) {
	    resolveClass(cl);
	}
	return cl;
    }

    private Class loadClass(String name, URL url) throws IOException {
	InputStream in = null;

	try {
	    URLConnection c = url.openConnection();
	    c.setAllowUserInteraction(false);
	    in = HttpURLConnection.openConnectionCheckRedirects(c);

	    int len = c.getContentLength();
	    byte data[] = new byte[(len == -1) ? 4096 : len];
	    int total = 0, n;
		
	    while ((n = in.read(data, total, data.length - total)) >= 0) {
		if ((total += n) == data.length) {
		    if (len < 0) {
			byte newdata[] = new byte[total * 2];
			System.arraycopy(data, 0, newdata, 0, total);
			data = newdata;
		    } else {
			break;
		    }
		}
	    }
	    if (verbose)
		System.err.println("load:" + name + "\t" + total + "bytes");
	    in.close();
	    in = null;
	    return defineClass(name, data, 0, total);
	} catch (IOException e) {
	    e.printStackTrace();
	    throw e;
	} finally {
	    if (in != null) {
		in.close();
		System.gc();
		System.runFinalization();
	    }
	}
    }

    public static ClassLoader bootLoader() {
	String url = getProperty("compile.URL");
	if (url == null)
	    return null;
	if (getProperty("compile.verbose") != null)
	    verbose = true;
  	try {
  	    URL base = new URL(url);
  	    ClassLoader loader = new OpenJITLoader(base);
  	    return loader;
  	} catch(Exception e) {
  	    e.printStackTrace();
  	    return null;
  	}
    }
}
